package com.cw.jeeyt.common.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ResourceBundle;

import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.cw.jeeyt.common.Constants;

/**
 * 将文件转成swf格式
 *
 * @author chenw
 */
public class ConvertSwf {
    private static Logger logger = LoggerFactory.getLogger(ConvertSwf.class);
    @Value("flexPaperSwf_path")
    private static String flexPaperSwf_path;

    /**
     * 入口方法-通过此方法转换文件至swf格式
     *
     * @param filePath 上传文件所在文件夹的绝对路径
     * @param fileName 文件名称
     * @return 生成swf文件名
     * @throws Exception
     */
    public static String beginConvert(String filePath, String fileName) throws Exception {
        final String DOC = ".doc";
        final String DOCX = ".docx";
        final String XLS = ".xls";
        final String XLSX = ".xlsx";
        final String PDF = ".pdf";
        final String SWF = ".swf";
        final String JPG = ".jpg";
        final String JPEG = ".jpeg";
        final String GIF = ".gif";
        final String PNG = ".png";
        String toolFile = "flexPaper/pdf2swf.exe";
        toolFile = Thread.currentThread()
            .getContextClassLoader()
            .getResource("../../")
            .getPath()
            .substring(1) + toolFile;
        System.out.println(toolFile);
        String outFile = "";
        String fileNameOnly = "";
        String fileExt = "";
        if (null != fileName && fileName.indexOf(".") > 0) {
            int index = fileName.indexOf(".");
            fileNameOnly = fileName.substring(0, index);
            fileExt = fileName.substring(index)
                .toLowerCase();
        }
        String inputFile = filePath + File.separator + fileName;
        String outputFile = "";
        boolean isTempFile = false;
        // 如果是office文档，先转为pdf文件
        if (fileExt.equals(DOC) || fileExt.equals(DOCX) || fileExt.equals(XLS) || fileExt.equals(XLSX)
            || fileExt.equals(JPG) || fileExt.equals(JPEG) || fileExt.equals(GIF) || fileExt.equals(PNG)) {
            outputFile = filePath + File.separator + fileNameOnly + PDF;
            office2PDF(inputFile, outputFile);
            inputFile = outputFile;
            fileExt = PDF;
            isTempFile = true;
        }

        if (fileExt.equals(PDF)) {
            outputFile = filePath + File.separator + fileNameOnly + SWF;
            convertPdf2Swf(inputFile, outputFile, toolFile);
            outFile = outputFile;
            if (isTempFile)// 如果是生成的中间PDF文件，需要删除
            {
                File f = new File(inputFile);
                f.delete();
            }
        }
        return outFile;
    }

    /**
     * 入口方法-通过此方法转换文件至swf格式
     *
     * @param pdfOutputPath 上传文件所在文件夹的绝对路径
     * @param fileName 文件名称
     * @return 生成swf文件名
     */
    public static String convertPDF(String fileName, String pdfOutputPath, String swfOutputPath) throws Exception {
        final String DOC = ".doc";
        final String DOCX = ".docx";
        final String XLS = ".xls";
        final String XLSX = ".xlsx";
        final String PDF = ".pdf";
        final String SWF = ".swf";
        final String JPG = ".jpg";
        final String JPEG = ".jpeg";
        final String GIF = ".gif";
        final String PNG = ".png";

        String toolFile = SystemPath.getSysPath() + Constants.SWF_EXE_PATH;
        String outFile = "";
        String fileNameOnly = "";
        String fileExt = "";
        if (null != fileName && fileName.indexOf(".") > 0) {
            int index = fileName.indexOf(".");
            fileNameOnly = fileName.substring(0, index);
            fileExt = fileName.substring(index)
                .toLowerCase();
        }
        String inputFile = pdfOutputPath + File.separator + fileName;
        boolean isTempFile = false;
        // 如果是office文档，先转为pdf文件
        if (fileExt.equals(DOC) || fileExt.equals(DOCX) || fileExt.equals(XLS) || fileExt.equals(XLSX)
            || fileExt.equals(JPG) || fileExt.equals(JPEG) || fileExt.equals(GIF) || fileExt.equals(PNG)) {
            pdfOutputPath = pdfOutputPath + File.separator + fileNameOnly + PDF;
            office2PDF(inputFile, pdfOutputPath);
            inputFile = pdfOutputPath;
            fileExt = PDF;
            isTempFile = true;
        }

        if (fileExt.equals(PDF)) {
            swfOutputPath = swfOutputPath + File.separator + fileNameOnly + SWF;
            convertPdf2Swf(inputFile, swfOutputPath, toolFile);
            outFile = swfOutputPath;
            if (isTempFile)// 如果是生成的中间PDF文件，需要删除
            {
                File f = new File(inputFile);
                f.delete();
            }
        }
        return outFile;
    }

    /**
     * 将pdf文件转换成swf文件
     *
     * @param sourceFile pdf文件绝对路径
     * @param outFile swf文件绝对路径
     * @param toolFile 转换工具绝对路径
     */
    private static void convertPdf2Swf(String sourceFile, String outFile, String toolFile) throws Exception {
        String command = toolFile + " \"" + sourceFile + "\" -o  \"" + outFile + "\" -s flashversion=9 ";
        //Process process = Runtime.getRuntime().exec(command);
        Runtime.getRuntime()
            .exec(command);
        //System.out.println(loadStream(process.getInputStream()));
        //System.err.println(loadStream(process.getErrorStream()));
        //System.out.println(loadStream(process.getInputStream()));
        logger.info("###--Msg: swf 转换成功，输出路径：{}", outFile);
    }

    /**
     * office文档转pdf文件
     *
     * @param sourceFile office文档绝对路径
     * @param destFile pdf文件绝对路径
     * @return
     */
    private static int office2PDF(String sourceFile, String destFile) throws Exception {
        ResourceBundle rb = ResourceBundle.getBundle("system");
        String OpenOffice_HOME = rb.getString("openOffice_Home");
        // String host_Str = rb.getString("oo_host");
        // String port_Str = rb.getString("oo_port");
        File inputFile = new File(sourceFile);
        if (!inputFile.exists()) {
            return -1; // 找不到源文件
        }
        // 如果目标路径不存在, 则新建该路径
        File outputFile = new File(destFile);
        if (!outputFile.getParentFile()
            .exists()) {
            outputFile.getParentFile()
                .mkdirs();
        }
        OfficeManager officeManager = new DefaultOfficeManagerConfiguration().setOfficeHome(OpenOffice_HOME)
            .buildOfficeManager();
        officeManager.start();

        OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
        converter.convert(new File(sourceFile), new File(destFile));

        officeManager.stop();

        return 0;

    }

    static String loadStream(InputStream in) throws IOException {
        int ptr = 0;
        in = new BufferedInputStream(in);
        StringBuffer buffer = new StringBuffer();

        while ((ptr = in.read()) != -1) {
            buffer.append((char) ptr);
        }
        return buffer.toString();
    }

}
